package com.example.web.service.impl;

import com.example.web.entity.AnalysisData;
import com.example.web.entity.Customer;
import com.example.web.mapper.CustomerMapper;
import com.example.web.mapper.InteractionRecordMapper;
import com.example.web.service.AnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 智能分析服务实现类
 */
@Service
public class AnalysisServiceImpl implements AnalysisService {
    
    @Autowired
    private CustomerMapper customerMapper;
    
    @Autowired
    private InteractionRecordMapper interactionRecordMapper;
    
    @Override
    public List<AnalysisData.AlertInfo> getAlertInfo(Long creatorId) {
        List<AnalysisData.AlertInfo> alerts = new ArrayList<>();
        
        // 检查已流失客户占比
        checkLostCustomersRatio(creatorId, alerts);
        
        // 检查7天内无新增客户
        checkNoNewCustomersIn7Days(creatorId, alerts);
        
        return alerts;
    }
    
    @Override
    public List<AnalysisData.CustomerTrendData> getCustomerTrendData(Long creatorId) {
        List<AnalysisData.CustomerTrendData> trendData = new ArrayList<>();
        
        // 获取近30天的日期范围
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(29);
        
        // 获取每天的新增客户数据
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            LocalDateTime dayStart = date.atStartOfDay();
            LocalDateTime dayEnd = date.atTime(23, 59, 59);
            
            // 获取当天新增的客户列表
            List<Customer> dailyCustomers = customerMapper.findCustomersByDateRange(
                creatorId, dayStart, dayEnd);
            
            AnalysisData.CustomerTrendData dataPoint = new AnalysisData.CustomerTrendData();
            dataPoint.setDate(date);
            dataPoint.setCount(dailyCustomers.size());
            dataPoint.setCustomers(dailyCustomers);
            
            trendData.add(dataPoint);
        }
        
        return trendData;
    }
    
    @Override
    public Map<String, Object> getHighValueCustomers(Long creatorId, Integer page, Integer size, String keyword) {
        // 设置默认值
        if (page == null || page < 1) page = 1;
        if (size == null || size < 1) size = 10;
        
        // 获取高价值客户列表
        List<AnalysisData.HighValueCustomer> allHighValueCustomers = getHighValueCustomersList(creatorId, keyword);
        
        // 分页处理
        int total = allHighValueCustomers.size();
        int startIndex = (page - 1) * size;
        int endIndex = Math.min(startIndex + size, total);
        
        List<AnalysisData.HighValueCustomer> pagedCustomers = new ArrayList<>();
        if (startIndex < total) {
            pagedCustomers = allHighValueCustomers.subList(startIndex, endIndex);
        }
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", pagedCustomers);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);
        
        return result;
    }
    
    @Override
    public List<AnalysisData.HighValueCustomer> exportHighValueCustomers(Long creatorId, String keyword) {
        return getHighValueCustomersList(creatorId, keyword);
    }
    
    /**
     * 检查已流失客户占比
     */
    private void checkLostCustomersRatio(Long creatorId, List<AnalysisData.AlertInfo> alerts) {
        // 获取用户所有客户数量
        Long totalCustomers = customerMapper.countCustomers(creatorId, null, null);
        if (totalCustomers == 0) {
            return;
        }
        
        // 获取已流失客户数量
        Long lostCustomers = customerMapper.countCustomers(creatorId, "已流失", null);
        
        // 计算占比
        double lostRatio = (double) lostCustomers / totalCustomers * 100;
        
        if (lostRatio > 30) {
            AnalysisData.AlertInfo alert = new AnalysisData.AlertInfo();
            alert.setType("LOST_CUSTOMERS");
            alert.setMessage(String.format("已流失客户占比过高：%.1f%%，建议加强客户维护", lostRatio));
            alert.setLevel("DANGER");
            alert.setValue(lostRatio);
            alerts.add(alert);
        }
    }
    
    /**
     * 检查7天内无新增客户
     */
    private void checkNoNewCustomersIn7Days(Long creatorId, List<AnalysisData.AlertInfo> alerts) {
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        LocalDateTime now = LocalDateTime.now();
        
        // 获取最近7天新增客户数量
        List<Customer> recentCustomers = customerMapper.findCustomersByDateRange(
            creatorId, sevenDaysAgo, now);
        
        if (recentCustomers.isEmpty()) {
            AnalysisData.AlertInfo alert = new AnalysisData.AlertInfo();
            alert.setType("NO_NEW_CUSTOMERS");
            alert.setMessage("7天内无新增客户，建议加强客户开发");
            alert.setLevel("WARNING");
            alert.setValue(0.0);
            alerts.add(alert);
        }
    }
    
    /**
     * 获取高价值客户列表
     */
    private List<AnalysisData.HighValueCustomer> getHighValueCustomersList(Long creatorId, String keyword) {
        // 获取近7天内互动次数大于2次的已联系客户
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        LocalDateTime now = LocalDateTime.now();
        
        // 查询符合条件的客户（已联系客户或朋友推荐）
        List<Customer> eligibleCustomers = customerMapper.findHighValueCustomers(
            creatorId, sevenDaysAgo, now, keyword);
        
        List<AnalysisData.HighValueCustomer> highValueCustomers = new ArrayList<>();
        
        System.out.println("[DEBUG] 查询到符合条件的客户数量: " + eligibleCustomers.size());
        
        for (Customer customer : eligibleCustomers) {
            // 获取该客户的互动次数
            Integer interactionCount = interactionRecordMapper.countInteractionsByCustomerAndDateRange(
                customer.getId(), sevenDaysAgo, now);
            
            System.out.println(String.format("[DEBUG] 客户[%s] 近7天互动次数: %d, 状态: %s, 来源: %s", 
                customer.getName(), interactionCount, customer.getStatus(), customer.getSource()));
            
            if (interactionCount > 2) {
                // 获取最后一次互动时间
                String lastContactTime = interactionRecordMapper.getLastContactTime(customer.getId());
                
                AnalysisData.HighValueCustomer highValueCustomer = new AnalysisData.HighValueCustomer();
                highValueCustomer.setCustomerId(customer.getId());
                highValueCustomer.setCustomerName(customer.getName());
                highValueCustomer.setCompanyName(customer.getCompanyName());
                highValueCustomer.setInteractionCount(interactionCount);
                highValueCustomer.setLastContactTime(lastContactTime);
                highValueCustomer.setCustomerStatus(customer.getStatus());
                
                highValueCustomers.add(highValueCustomer);
            }
        }
        
        System.out.println("[DEBUG] 最终筛选出的高价值客户数量: " + highValueCustomers.size());
        
        // 按互动次数降序排序
        highValueCustomers.sort((a, b) -> b.getInteractionCount().compareTo(a.getInteractionCount()));
        
        return highValueCustomers;
    }
}